<?php

namespace App\Servers\WebSocket\Utils;



class Response
{
    private static $instance;

    private $scope = '';
    private $op = '';
    private $data = [];
    private $error = [];
    private $dataTye = 'json';

    protected function reset()
    {
        $this->scope = '';
        $this->data = [];
        $this->dataTye = 'json';
    }

    public static function getInstance(): Response
    {
        if (!self::$instance) {
            self::$instance = new Response();
        }
        return self::$instance;
    }


    public function data($scope, $data,$op = ''): Response
    {
        $this->scope = $scope;
        $this->data = $data;
        $this->op = $op;
        return $this;
    }

    public function error($scope, $errCode = -1, $message = '',$detail = ''): Response
    {
        $this->scope = $scope;
        $this->error = ['code'=>$errCode,'message'=>$message,'detail'=>$detail];
        return $this;
    }

    public function json(): Response
    {
        return $this;
    }

    public function end(): mixed
    {
        $ret = ['scope' => $this->scope,'op' => $this->op, 'data' => $this->data,'error'=>$this->error];
        if ($this->dataTye == 'json' || !$this->dataTye) {
            $ret = json_encode($ret);
        }
        $this->reset();
        return $ret;
    }
}
